package com.loren.demo04.delay_message;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedissonDelayQueue {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private final RBlockingQueue<String> blockingQueue;

    private final RDelayedQueue<String> delayQueue;

    public RedissonDelayQueue(RBlockingQueue<String> blockingQueue, RDelayedQueue<String> delayQueue) {
        this.blockingQueue = blockingQueue;
        this.delayQueue = delayQueue;
    }

    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.submit(() -> {
            while (true) {
                try {
                    String message = blockingQueue.take();
                    log.info("receive -> message = {}, receiveTime = {}", message, FORMATTER.format(LocalDateTime.now()));
                } catch (Exception e) {
                    log.error(e.getMessage());
                    break;
                }
            }
        });
    }

    public void offerTask(String message, long second) {
        log.info("publish -> publishTime = {}, delaySecond = {}", FORMATTER.format(LocalDateTime.now()), second);
        this.delayQueue.offer(message, second, TimeUnit.SECONDS);
    }
}